package com.javasm.controller.B2CController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.javasm.common.http.AxiosResult;
import com.javasm.common.page.PageResult;
import com.javasm.common.perm.HasPerm;
import com.javasm.controller.base.BaseController;
import com.javasm.controller.stockController.SalesOutboundController;
import com.javasm.domin.criteria.orderCriteria.OrderCriteria;
import com.javasm.domin.criteria.orderCriteria.OrderGoodsCriteria;
import com.javasm.domin.criteria.orderCriteria.OrderProductCriteria;
import com.javasm.domin.entity.orderEntity.*;
import com.javasm.domin.entity.stockEntity.OutBriefList;
import com.javasm.domin.entity.stockEntity.OutDetailedOrder;
import com.javasm.domin.vo.orderVo.OrderAndReceiver;
import com.javasm.domin.vo.orderVo.OrderGoodVo;
import com.javasm.domin.vo.orderVo.OrderVo;
import com.javasm.domin.vo.orderVo.ProductVo;
import com.javasm.mapper.B2cOrderMapper.B2cReceiverMapper;
import com.javasm.mapper.B2cOrderMapper.OrderGoodsMapper;
import com.javasm.mapper.B2cOrderMapper.OrderMapper;
import com.javasm.service.B2cOrderService.OrderGoodsService;
import com.javasm.service.B2cOrderService.OrderService;
import com.javasm.transfer.orderTransfer.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.ls.LSInput;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.javasm.common.dictionary.InitContext.dic;

/**
 * @Author：liyangsong
 * @Version：1.0
 * @Date：2021/11/18-20:33
 * @Since:jdk1.8
 * @Description:
 */

@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController extends BaseController {
    @Resource
    private OrderService orderService;
    private final OrderGoodsTransfer orderGoodsTransfer;
    @Resource
    private SalesOutboundController salesOutboundController;
    private final OrderGoodsService orderGoodsService;
    private final OrderMapper orderMapper;

    @RequestMapping("/h")
    public List<B2cOrder> find() {
        return orderService.list();
    }

    //    /**
//     * 联表查询
//     * @return
//     */
    @RequestMapping("lian")
    public List<OrderAndReceiver> list() {
        return orderService.findList();
    }

    /**
     * 分页查询
     *
     * @param orderCriteria
     * @return
     */
    @RequestMapping("/page")
    public AxiosResult<PageResult<OrderAndReceiver>> find(OrderCriteria orderCriteria) {
        PageResult<OrderAndReceiver> result = orderService.search(orderCriteria);
        return AxiosResult.success(result);
    }

    /**
     * 数据字典
     *
     * @return
     */
    @RequestMapping("/dic")
    public AxiosResult<Map<Integer, LinkedHashMap<Integer, String>>> data() {
        return AxiosResult.success(dic);
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping("/findById/{id}")
    public AxiosResult<B2cOrder> find(@PathVariable Serializable id) {
        B2cOrder b2cOrder = orderService.getById(id);
        return AxiosResult.success(b2cOrder);
    }

    /**
     * 批量查询订单
     *
     * @param idList
     * @return
     */
    @RequestMapping("/f/{idList}")
    public AxiosResult<List<OrderAndReceiver>> findList(@PathVariable List<Serializable> idList) {
        List<OrderAndReceiver> byIdList = orderService.findByIdList(idList);
        System.out.println(byIdList);
        return AxiosResult.success(byIdList);
    }

    /**
     * 生成销售出库单
     *
     * @return
     */
    @RequestMapping("/order/outStock/{idList}")
    @ResponseBody
    public AxiosResult<Boolean> hj(@PathVariable List<Serializable> idList, OrderGoodsCriteria orderGoodsCriteria) {
        //批量生成出库单
        List<OrderAndReceiver> byIdList = orderService.findByIdList(idList);
        //new 出库单对象
        //根据idList查询的对象 赋值给出库单
        for (int i = 0; i < byIdList.size(); i++) {
            OutBriefList outBriefList = new OutBriefList();
            OrderAndReceiver orderAndReceiver = byIdList.get(i);
            outBriefList.setBusinessType(orderAndReceiver.getBusinessType());
//           outBriefList.setOrderDate(orderAndReceiver.getCreateTime());
            Integer integer = new Integer(String.valueOf(orderAndReceiver.getId()));
            outBriefList.setDetailOrderId(Math.toIntExact(orderAndReceiver.getId()));
            outBriefList.setPayType(orderAndReceiver.getPaymentMethodId());
            outBriefList.setOrderStatus(orderAndReceiver.getOrderStatus());
            outBriefList.setVipAccount(orderAndReceiver.getVipId());
            Date date = Date.from( orderAndReceiver.getOrderDate().atZone( ZoneId.systemDefault()).toInstant());
            outBriefList.setOrderDate(date);
            outBriefList.setOrderType(orderAndReceiver.getOrderType());
            salesOutboundController.insertBriefOrder(outBriefList);
        }

        orderGoodsCriteria.setOrderIdList(idList);
        //根据订单idList  批量查询订单下商品
        List<OrderGoodVo> orderGoodByOrderIdList = orderGoodsService.findOrderGoodByOrderIdList(orderGoodsCriteria);
        System.out.println(orderGoodByOrderIdList);
        //得到要插入的对象
        for (int i = 0; i < orderGoodByOrderIdList.size(); i++) {
            OutDetailedOrder outDetailedOrder = new OutDetailedOrder();
            OrderGoodVo orderGoodVo = orderGoodByOrderIdList.get(i);
            outDetailedOrder.setOrderId(orderGoodVo.getOrderId());
            outDetailedOrder.setGoodsColor(orderGoodVo.getColorId());
            outDetailedOrder.setGoodsId(orderGoodVo.getGoodsId());
            outDetailedOrder.setGoodsName(orderGoodVo.getOrderProductName());
            outDetailedOrder.setGoodsNum(orderGoodVo.getOrderProductNumber());
            salesOutboundController.insertDetailedOrder(outDetailedOrder);
        }

        Boolean aBoolean = true;
        return AxiosResult.success(aBoolean);
    }

    /**
     * 出库之后更改订单状态
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/update/{orderId}")
    public AxiosResult<Integer> update(@PathVariable Serializable orderId) {
        Integer integer = orderMapper.updateOrderStatus(orderId);
        return AxiosResult.success(integer);
    }

    /**
     * 发送出库提醒之后更改订单状态，出库待审核
     *
     * @param orderIdList
     * @return
     */
    @RequestMapping("/up/{orderIdList}")
    public AxiosResult<Integer> up(@PathVariable List<Serializable> orderIdList) {
        Integer integer = 0;
        for (Serializable serializable : orderIdList) {
            integer = orderMapper.updateStatus(serializable);
        }

        return AxiosResult.success(integer);
    }


    /**
     * 添加订单
     *
     * @param b2cOrder
     * @return
     */
    public AxiosResult<Integer> add(@RequestBody B2cOrder b2cOrder) {
        int insert = orderMapper.insert(b2cOrder);
        return AxiosResult.success();
    }

    /**
     * 根据订单id得到订单信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/findOrder/{id}")
    public AxiosResult<OrderAndReceiver> show(@PathVariable Serializable id) {
        OrderAndReceiver orderInfo = orderService.findOrderInfo(id);
//        B2cOrder b2cOrder = orderMapper.selectById(id);
        return AxiosResult.success(orderInfo);
    }


    //    ////////////////////////////////////////////////////////////
    private final OrderExcelTransfer orderExcelTransfer;
    private final OrderTransfer orderTransfer;
    private final OrderGoodsMapper orderGoodsMapper;
    private final OrderGoodExcelTransfer orderGoodExcelTransfer;
    private final B2cReceiverMapper b2cReceiverMapper;
    private final OrderReceiverTransfer orderReceiverTransfer;

    @RequestMapping("/exportExcel/{idList}")
    public ResponseEntity<byte[]> export(@PathVariable List<Serializable> idList) throws UnsupportedEncodingException {
        //根据ID批量得到值
        List<B2cOrder> b2cOrderList = orderMapper.selectBatchIds(idList);
        List<B2cOrderExcel> escape = orderExcelTransfer.Escape(b2cOrderList);
        //得到商品
        List<B2cOrderGoods> byOrderList = orderGoodsMapper.findByOrderList(idList);
        List<B2cOrderGoodsExcel> b2cOrderGoodsExcels = orderGoodExcelTransfer.toVO(byOrderList);
        //收货人信息
        List<B2cReceiver> byOrderIdList = b2cReceiverMapper.findByOrderIdList(idList);
        List<B2cReceiverExcel> b2cReceiverExcels = orderReceiverTransfer.toVO(byOrderIdList);
        //输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //写入
        ExcelWriter excelWriter = EasyExcel.write(out, B2cOrderExcel.class).build();

        WriteSheet writeSheet = EasyExcel.writerSheet("订单信息表").build();
        excelWriter.write(escape, writeSheet);
        //写入
        writeSheet = EasyExcel.writerSheet(1, "商品信息表").head(B2cOrderGoodsExcel.class).build();
        excelWriter.write(b2cOrderGoodsExcels, writeSheet);

        writeSheet = EasyExcel.writerSheet(2, "收货人信息表").head(B2cReceiverExcel.class).build();
        excelWriter.write(b2cReceiverExcels, writeSheet);

        excelWriter.finish();
        //写出
        byte[] bytes = out.toByteArray();
//        固定三写法
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachement", URLEncoder.encode("订单信息表.xlsx", "utf-8"));
        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
    }


}
